package managers
{
	import Utils.CommonInfoManager;
	
	import com.asfusion.mate.events.Dispatcher;
	
	import events.LoginEvent;
	
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.utils.ByteArray;
	
	import me2day.api.Me2day;
	import me2day.api.data.Me2dayCommentLogs;
	import me2day.api.data.Me2dayUser;
	import me2day.api.events.Me2dayErrorEvent;
	import me2day.api.events.Me2dayEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CollectionEvent;
	import mx.managers.CursorManager;
	
	public class Me2DayManager extends EventDispatcher
	{
		public function Me2DayManager()
		{
			initMe2dayobj();
		}
		
		private function initMe2dayobj():void
		{
			me2dayobj.addEventListener(Me2dayEvent.ON_COMMENT_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_CREATE_COMMENT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_CREATE_POST, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_FRIENDS_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_LATEST_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_NOOP, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_PERSON_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_METOOS_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_DOMETOO_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_SET_DESCRIPTION, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_GET_AUTH_URL_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_GET_FULL_AUTH_TOKEN_RESULT, OnMe2dayEvent);
			me2dayobj.addEventListener(Me2dayEvent.ON_GET_TRACK_COMMENTS_RESULT, OnMe2dayEvent);
			
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_COMMENTSLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_CREATECOMMENTLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_CREATEPOSTLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_DOMETOOLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_FRIENDSLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_LATESTLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_METOOSLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_NOOPLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_PERSONLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_SETDESCRIPTIONLOADER, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_GETAUTHURL, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_GETFULLAUTHTOKEN, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SERVICE_TYPE_GETTRACKCOMMENTS, OnMe2dayErrorEvent);
			me2dayobj.addEventListener(Me2dayErrorEvent.SECURITY_ERROR, OnMe2dayErrorEvent);
		}
		
		private var errormap:Object = {
			"401":"인증에 실패하였습니다.",
    		"403":"제공하지 않는 데이터입니다.",
    		"500":"Internal Server Error: 요청처리시 발생한 오류입니다.",
    		"301":"Moved Permanently: me2API 요청 URL이 변경되었습니다."
    		/*200":"OK: 정상적으로 처리된 경우입니다. */
		};	
				
		private function checkError(event:Me2dayEvent):Boolean
		{
			var errorcode:Number = event.data as Number;
			if ( errorcode )
			{
				var errorstr:String = errormap[errorcode.toString()];
				if ( errorstr )
				{
					Alert.show(errorstr, "me2DC 에러");
					return false;
				}
			}
			return true;
		}
		
		private function OnMe2dayErrorEvent(event:Me2dayErrorEvent):void
		{
			var errorEvent:Me2dayErrorEvent = new Me2dayErrorEvent(event.type, true);
			errorEvent.message = event.message;
			dispatcher.dispatchEvent(errorEvent);
			trace("me2DC 에러:" + event.message);
		}
		
		private function OnMe2dayEvent(event:Me2dayEvent):void
		{
			CursorManager.removeAllCursors();
			
			if ( !checkError(event) )
				return;
			
			switch ( event.type )
			{
				case Me2dayEvent.ON_COMMENT_RESULT:
					OnCommentResult(event);
					break;
				case Me2dayEvent.ON_CREATE_COMMENT:
					OnCreateComment(event);
					break;
				case Me2dayEvent.ON_CREATE_POST:
					OnCreatePost(event);
					break;
				case Me2dayEvent.ON_FRIENDS_RESULT:
					OnFriendsResult(event);
					break;
				case Me2dayEvent.ON_LATEST_RESULT:
					OnLatestsResult(event);
					break;
				case Me2dayEvent.ON_NOOP:
					OnNoop(event);
					break;
    			case Me2dayEvent.ON_PERSON_RESULT:
    				OnPersonResult(event);
    				break;    		
				case Me2dayEvent.ON_METOOS_RESULT:
    				OnMetoosResult(event);
    				break;    		
				case Me2dayEvent.ON_DOMETOO_RESULT:
    				OnDoMetooResult(event);
    				break;    		
				case Me2dayEvent.ON_SET_DESCRIPTION:
    				OnSetDescription(event);
    				break;    		
				case Me2dayEvent.ON_GET_AUTH_URL_RESULT:
    				OnGetAuthUrl(event);
    				break;    		
				case Me2dayEvent.ON_GET_FULL_AUTH_TOKEN_RESULT:
    				OnGetFullAuthToken(event);
    				break;    		
				case Me2dayEvent.ON_GET_TRACK_COMMENTS_RESULT:
    				OnGetTrackCommentsResult(event);
    				break;    		
				default :
					break;		  		
			}
		}
		
		private var me2dayobj:Me2day = new Me2day;
		public function setAuth(id:String, key:String):void
		{
			me2dayobj.setAuth(id, key);		
			CommonInfoManager.userid = id;
			CommonInfoManager.appkey = key;	
			
			me2dayobj.noop();			
		}
		
		public function getAuthUrl():void
		{
			me2dayobj.getAuthUrl();
		}
		
		private function OnGetAuthUrl(event:Me2dayEvent):void
		{
			if ( event.data.hasOwnProperty("url") )
			{
				var u:URLRequest = new URLRequest(event.data["url"]);
				navigateToURL(u,"_blank"); 
			}
		}
		
		public function getFullAuthToken():void
		{
			me2dayobj.getFullAuthToken();
		}
		
		public function setFullAuthToken(token:String):void
		{
			me2dayobj.setFullAuthToken(token);
			me2dayobj.setAuth(CommonInfoManager.userid, "");
			getPerson();
			dispatcher.dispatchEvent(new LoginEvent(LoginEvent.OK));
		}
		
		private function OnGetFullAuthToken(event:Me2dayEvent):void
		{
			if ( event.data.hasOwnProperty("user_id") )
				CommonInfoManager.userid = event.data["user_id"];
			if ( event.data.hasOwnProperty("full_auth_token") )
				CommonInfoManager.fullAuthToken = event.data["full_auth_token"];
			
			me2dayobj.setAuth(CommonInfoManager.userid, "");
			getPerson();
			dispatcher.dispatchEvent(new LoginEvent(LoginEvent.OK));
		}
		
		private var isGetLatestForFriend:Boolean;
		public function getLatest(id:String = null):void
		{
			CursorManager.setBusyCursor();
			
			if ( latests )
			{
				latests = new ArrayCollection;
				latests.dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE));
			}
			
			if ( id )
			{
				isGetLatestForFriend = true;
				me2dayobj.loadLatest(id);				
			}
			else
			{
				isGetLatestForFriend = false;
				me2dayobj.loadLatest(CommonInfoManager.userid);		
				
			}					
		}
		
		public function getPerson():void
		{
			me2dayobj.loadPerson(CommonInfoManager.userid);
		}
		
		public function getComments(post_id:String):void
		{
			CursorManager.setBusyCursor();
			
			me2dayobj.loadComments(post_id);
		}
		private function OnCommentResult(event:Me2dayEvent):void
		{
			for each ( var item:Object in latests )
			{
				if ( item.post_id == event.data.post_id )
				{
					item.comments = event.data.comments;
					var evt:Me2dayEvent = new Me2dayEvent(event.type);
					evt.data.post_id = event.data.post_id;
					dispatcher.dispatchEvent(evt);		
				}
			}						
		}
		
		public function OnSetDescription(event:Me2dayEvent):void
		{
			var evt:Me2dayEvent = new Me2dayEvent(event.type, true);
			dispatcher.dispatchEvent(evt);	
		}
		
		private var metoosReceiver:EventDispatcher;
		
		public function getMetoos(ed:EventDispatcher, post_id:String):void
		{
			metoosReceiver = ed;
			me2dayobj.loadMetoos(post_id);
		}
		
		private function OnMetoosResult(event:Me2dayEvent):void
		{
			var evt:Me2dayEvent = new Me2dayEvent(event.type);
			evt.data.metoos = event.data.metoos;
			metoosReceiver.dispatchEvent(evt);	
		}
		
		private var doMetooReceiver:EventDispatcher;
		public function doMetoo(ed:EventDispatcher, post_id:String):void
		{
			doMetooReceiver = ed;
			me2dayobj.doMetoo(post_id);
		}
		
		private function OnDoMetooResult(event:Me2dayEvent):void
		{
			var evt:Me2dayEvent = new Me2dayEvent(event.type);
			evt.data.code = event.data.code;
			evt.data.message = event.data.message;
			evt.data.description = event.data.description;
			doMetooReceiver.dispatchEvent(evt);	
		}
		
		public function createPost(body:String, tags:String, icon:String, attachment:ByteArray, sms:Boolean,
									longitude:Number, latitude:Number):void
		{
			CursorManager.setBusyCursor();
			
			me2dayobj.createPost(body, tags, icon, attachment, sms, longitude, latitude);
		}
		private var dispatcher:Dispatcher = new Dispatcher;
		
		private function OnCreatePost(event:Me2dayEvent):void
		{
			var e:Me2dayEvent = new Me2dayEvent(event.type);
			e.data = event.data;
			dispatcher.dispatchEvent(e);
		}
		
		private var curPostItem:EventDispatcher;
		public function createComment(postItem:EventDispatcher, post_id:String, comment:String):void
		{
			CursorManager.setBusyCursor();
			
			curPostItem = postItem;
			me2dayobj.createComment(post_id, comment);
		}
		
		private function OnCreateComment(event:Me2dayEvent):void
		{
			curPostItem.dispatchEvent(new Me2dayEvent(event.type));
		}
		
		public function getFriends():void
		{
			CursorManager.setBusyCursor();
			
			me2dayobj.loadFriends(CommonInfoManager.userid, CommonInfoManager.friendType);
		}
		
		public function setDescription(description:String):void
		{
			CursorManager.setBusyCursor();
			
			me2dayobj.setDescription(description);
		}
		
		public function trackComments():void
		{
			me2dayobj.getTrackComments("to_me", CommonInfoManager.autoUpdateCommentsNum);
		}
		
		private function OnGetTrackCommentsResult(event:Me2dayEvent):void
		{
			var commentLogs:Me2dayCommentLogs = event.data.commentLogs as Me2dayCommentLogs;
			
			if ( !commentLogs || commentLogs.commentToMeArr.length == 0 )
				return;
			
			AutoUpdateManager.GetInstance().UpdateCommentLogs(commentLogs);
		}
		
		
		
		[Bindable]
		public var friends : ArrayCollection;
		private function OnFriendsResult(event:Me2dayEvent):void
		{
			var result:Array = event.data as Array;
			if ( result )
			{
				friends = new ArrayCollection(result);				
			}		
		}
		
		[Bindable]
		public var latests : ArrayCollection;
		
		private function OnLatestsResult(event:Me2dayEvent):void
		{
			var result:Array = event.data as Array;
			if ( result )
			{
				if ( isGetLatestForFriend )
				{
					result = result.slice(0, CommonInfoManager.friendPostCount);
				}
				latests = new ArrayCollection(result);				
			}						
		}
		private function OnNoop(event:Me2dayEvent):void
		{
			dispatcher.dispatchEvent(new LoginEvent(LoginEvent.OK));
			getPerson();
			trace(event.type + ":" + event.data);
		}
		
		[Bindable] public var id:String;
		[Bindable] public var nickname:String;
		[Bindable] public var face:String;
		[Bindable] public var description:String;
		private function OnPersonResult(event:Me2dayEvent):void
		{
			var result:Me2dayUser = event.data as Me2dayUser;
			if ( result )
			{
				id = "<a href='http://me2day.net/" + result.id + "'>" + result.id + "</a>";
				if ( result.homepage )
				{
					nickname = "<a href='" + result.homepage + "'>" + result.nickname + "</a>";
				}
				else
				{
					nickname = result.nickname;
				}
				face = result.face;
				description = result.description;
				
				CommonInfoManager.user = result;
			}	
			dispatcher.dispatchEvent(new Me2dayEvent(event.type));
		}

	}
}